package com.bw.shopping.time;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.LogUtils;

import java.lang.ref.WeakReference;
import java.sql.Time;


public class TimeService extends Service {

    public long time = 0;
    private TimeThread timeThread;
    private TimeHandel handel;
    private GetTime getTimesss;

    public GetTime getGetTimesss() {
        return getTimesss;
    }

    public void setGetTimesss(GetTime getTimesss) {
        this.getTimesss = getTimesss;
    }

    public TimeService() {
    }

    public interface GetTime{
        void myTime(long myTime);
    }


    //除了第一次调用onCrate 其余每次都调用onStartCommand
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        time = intent.getLongExtra("time",0);
        handel = new TimeHandel(this);
        timeThread = new TimeThread(handel);
        timeThread.start();
        return START_NOT_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }


    @Override
    public IBinder onBind(Intent intent) {
        return new TimeBinder();
    }

    public  class TimeBinder extends Binder{
        public TimeService getService(){
            return TimeService.this;
        }
    }


    @Override
    public void onDestroy() {

        //打断 关闭timeThread
        timeThread.interrupt();
        super.onDestroy();
    }

    public long getTime(){
        return time;
    }

    public  class TimeHandel extends Handler{

        //弱引用
        private WeakReference<TimeService> weakReference;

        public TimeHandel(TimeService service){
            weakReference = new WeakReference<>(service);
        }
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0){
                if (weakReference == null)
                    return;
                if (weakReference.get() == null)
                    return;
                weakReference.get().time+=1;
                if (getTimesss!=null){
                    getTimesss.myTime(weakReference.get().time);
                }
            }
        }
    }
}
